<template>
  <div class="h-box">
    <!-- 导航 -->
    <nav class="navbar bg-black">
      <div class="ms-2 fw-bold fs-3">Star Universe</div>
      <div class=" me-2 light fs-7 fw-light d-flex justify-content-between align-items-center ">
        <span class="sel-lang">语言选择</span>
        <span class="h-lang d-flex align-items-center">
          <img src="../assets/img/x1.png" alt="" />
        </span>
      </div>
    </nav> <!-- 轮播图 -->
    <div id="hCarousel" class="carousel slide" data-bs-ride="carousel">
      <div class="carousel-indicators">
        <button type="button" data-bs-target="#hCarousel" :data-bs-slide-to="index" v-for="(img,index) in bannerImgs" :key="index" :class="index == 0 ?'active':''" :aria-current="index == 0 ?true:false" :aria-label="'Slide '+ index"></button>
      </div>
      <div class="carousel-inner">
        <div class="carousel-item" :class="index == 0?'active':''" v-for="(img,index) in bannerImgs" :key="index">
          <img :src="img.url" class="d-block w-100" style="height:14em" alt="..." />
          <div class="carousel-caption d-md-block text-main">
            <!-- <p class="fs-1-3 mb-0 fw-light">星宇宙</p> -->
            <!-- <p>Star Universe</p> -->
          </div>
        </div>
      </div>
    </div> <!--  -->
    <div class="h-box-start">
      <div class="container">
        <!-- 星球？ -->
        <div class="row">
          <div class="col">
            <img src="../assets/img/star.png" class="img-fluid w-75 mx-auto d-block" alt="..." @click="openLotteryFeePopup" />

          </div>
        </div> <!-- ABCD -->
        <div class="row">
          <div class="col">
            <div class="d-flex justify-content-between h-box-star-sold">

              <div class="h-star bgimg-1 rounded-3" v-for="mystery in mysteryLists" :key="mystery.cardType">
                <span class="h-code d-block ms-1">{{mystery.cardType}}</span>
                <div class="mt-4 mx-2 h-img">
                  <img class="img-fluid rounded-3" :src="mystery.path" alt="" />
                  <div class="text-center py-2 text-truncate">{{mystery.number}}张</div>
                </div>
                <div class="text-center fs-7 fw-light my-1" @click="showSoldPopup(mystery)">卖出 </div>
              </div>

            </div>
          </div>
        </div> <!-- 兑换 -->
        <div class="row mt-3">
          <div class="col">
            <div class="bg-main rounded-2 p-2">
              <!-- item -->
              <div class="d-flex justify-content-between my-2" v-for="exlist in exchangeList" :key="exlist.id">
                <div class="w-50 d-flex align-items-center">
                  <div class="w-100">{{exlist.name}}</div>
                </div>
                <div class="w-25 text-end d-flex align-items-center">
                  <div class="w-100">{{exlist.suNumber}}SU</div>
                </div>
                <div class="w-25 d-flex align-items-center justify-content-end"><button type="button" class=" btn btn-sm btn-primary w-75" @click="openExchangePopup(exlist)">兑换</button> </div>
              </div> <!-- item -->

            </div>
          </div>
        </div> <!-- NFT卡牌空间 start -->
        <div class="row mt-4">
          <div class="col">
            <div class="h-card">
              <div class="h-card-title my-3 fs-5">
                <h5>NFT卡牌空间</h5>
              </div>
              <div class="h-card-box">
                <router-link to="/space">
                  <img src="../assets/img/card.png" class="w-100" alt="" />
                </router-link>
              </div>
            </div>
          </div>
        </div> <!-- NFT卡牌空间 end -->
        <!-- 新人加入 start -->
        <div class="row mt-4">
          <div class="col">
            <div class="h-card">
              <div class="h-card-title my-3 fs-5">
                <h5>新人加入</h5>
              </div>
              <div class="h-card-box bgimg-1 rounded-3 pb-1 pt-3 px-3">
                <div class="my-3 position-relative">
                  <input type="text" class=" w-100 bgc-1 border-0 rounded-3 py-1 ps-3 pe-6 text-main join-input" readonly="readonly" v-model="joinPrice" placeholder="100" />
                  <div class=" position-absolute top-50 end-0 translate-middle-y me-3 "> USDT </div>
                </div>
                <!-- <div class="my-3"> <input type="text" class=" w-100 bgc-1 border-0 rounded-3 py-1 px-3 text-main join-input " placeholder="请输入推荐人地址" /> </div> -->
                <!-- <div class="my-1">您的TRX钱包：--</div> -->
                <!-- <div class="my-1">USDT-TRC20 余额：--</div> -->
                <div class="my-4"> <button class="btn btn-primary w-75 d-block mx-auto btn-sm" type="button" @click="onJoin">立即加入</button></div>
              </div>
            </div>
          </div>
        </div>
        <!-- 新人加入 end -->

        <!-- 个人数据 start -->
        <div class="row mt-4">
          <div class="col">
            <div class="h-card">
              <div class="h-card-title my-3 fs-5">
                <h5>个人数据</h5>
              </div>
              <div class="h-card-box bgimg-1 rounded-3">
                <div class="bg-main rounded-2 p-2">
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-90 d-flex align-items-center">
                      <div class="w-100 text-truncate"> 我的合约地址：{{personalData.address}}</div>
                    </div>
                    <div class="w-10"> <img src="../assets/img/copy.png" class="float-end copy-img copy-btn1" alt="" :data-clipboard-text="personalData.address" /> </div>
                  </div>
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-50 d-flex align-items-center">
                      <div class="w-100">我的等级</div>
                    </div>
                    <div class="w-25 text-end d-flex align-items-center">
                      <div class="w-100">{{personalData.level}}</div>
                    </div>
                  </div>
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-90 d-flex align-items-center">
                      <div class="w-100 text-truncate"> 我的推荐人地址：{{personalData.upUserAddress}}</div>
                    </div>
                    <div class="w-10"> <img src="../assets/img/copy.png" class="float-end copy-img copy-btn2" alt="" :data-clipboard-text="personalData.upUserAddress" /> </div>
                  </div>
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-50 d-flex align-items-center">
                      <div class="w-100">我的有效直推地址数</div>
                    </div>
                    <div class="w-25 text-end d-flex align-items-center">
                      <div class="w-100">{{personalData.directNumber}}</div>
                    </div>
                  </div>
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-75 d-flex align-items-center">
                      <div class="w-100">我的团队有效地址数</div>
                    </div>
                    <div class="w-25 text-end d-flex align-items-center">
                      <div class="w-100">{{personalData.numberOfTeams}}</div>
                    </div>
                  </div>
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-25 d-flex align-items-center">
                      <div class="w-100">USDT余额</div>
                    </div>
                    <div class="w-50 text-end d-flex align-items-center">
                      <div class="w-100">{{personalData.usdtBalance}}</div>
                    </div>
                    <div class="w-25"><button type="button" class=" btn btn-sm btn-primary w-75 float-end" @click="onWithdraw(2)">提币</button> </div>
                  </div>
                  <!-- item -->
                  <!-- <div class="d-flex justify-content-between my-2">
                    <div class="w-50 d-flex align-items-center">
                      <div class="w-100">已提现奖金</div>
                    </div>
                    <div class="w-50 text-end d-flex align-items-center">
                      <div class="w-100">1000.0000</div>
                    </div>
                  </div> -->
                  <!-- item -->
                  <div class="d-flex justify-content-between my-2">
                    <div class="w-25 d-flex align-items-center">
                      <div class="w-100">SU余额</div>
                    </div>
                    <div class="w-50 text-end d-flex align-items-center">
                      <div class="w-100">{{personalData.suBalance}}</div>
                    </div>
                    <div class="w-25"> <button type="button" class=" btn btn-sm btn-primary w-75 float-end " @click="onWithdraw(1)">提币</button> </div>
                  </div>
                  <!-- item -->
                  <div class="d-flex justify-content-between my-3">
                    <div class="w-50"> <button type="button" class=" btn btn-primary w-75 " @click="onOpenRecharge">100SU充值</button> </div>
                    <div class="w-50"> <button type="button" class=" btn btn-primary w-75 float-end" @click="suTransaction">SU交易</button> </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div> <!-- 个人数据 end -->
        <!-- 规则解释 start -->
        <div class="row mt-4">
          <div class="col">
            <div class="h-card">
              <div class="h-card-title my-3 fs-5">
                <h5>规则解释</h5>
              </div>
              <div class="h-card-box h-rule-box bgimg-1 rounded-3 py-3 px-2">
                <h3>关于安全</h3>
                <p>区块链技术具有开放、自治、不可篡改等特性，因此所有投资者可以随时随地通过tron浏览器审计财务数据、任何人都没有办法私自篡改任何数据，从而保障规则的公平性和资金的安全性。</p>
                <h3>关于提币</h3>
                <p>传统金融领域提现一般都是由中心化的操盘方将您的收益转入到您的账户。去中心化的SU是将所有的规则都用代码的方式部署到tron公链上，且不可修改。没有操盘方，因此提现是由投资者自行点击页面上的按钮进行提现，随时随地都可以进行。</p>
                <h3>关于投资</h3>
                <p>SU智能合约部署在tron公链上，投资需要用tron公链代币USDT进行。每次投入金额为100USDT。</p>
                <h3>关于收益</h3>
                <p>总收益包括1种静态收益和2种动态收益。静态:投资100U获得SU礼包，每天解锁出一枚SU。动态：1、你邀请好友加入，你将获得好友投资数量的20%-40%作为佣金。2、如果您团队用户很多，还可以获得20%-30%的团队奖励。邀请参与的好友越多，您获得的佣金奖励也将越多，且佣金奖励是自动到账的。</p>
                <h3>关于合约池</h3>
                <p>用户投入的USDT会作为合约余额，此余额除按照合约既定规则进行转入转出以外，没有任何人可以人为干预，且任何人均可随时随地查看。既定规则规定:用户投入的USDT数量的70%完全分配，10%进入绿色公益计划，其余部分用户平级奖励以及回购等。</p>
              </div>
            </div>
          </div>
        </div>
        <!-- 规则解释 end -->
        <!-- 如何加入 start -->
        <div class="row mt-4">
          <div class="col">
            <div class="h-card">
              <div class="h-card-title my-3 fs-5">
                <h5>如何加入</h5>
              </div>
              <!-- step1 start -->
              <div class="row">
                <div class="col-2">
                  <div class="join-step d-flex align-content-between flex-column">
                    <div class="join-step-num active">1</div>
                    <div class="join-step-line active"></div>
                  </div>
                </div>
                <div class="col-10">
                  <div class="h-card-box bgimg-1 rounded-3 mt-1">
                    <div class="join-step-card px-2 py-3">
                      <h5>第一步: </h5>
                      <p>
                        你需要准备一个去中心化钱包.我们建议使用Tokenpocket/ Tronlink/ Tronmaski浏览器扩展或者 Trowalleta手机应用,你可以从https://tron.network/wallet下载。
                      </p>

                    </div>
                  </div>
                </div>
              </div>
              <!-- step2 start -->
              <div class="row">
                <div class="col-2">
                  <div class="join-step d-flex align-content-between flex-column">
                    <div class="join-step-num active">2</div>
                    <div class="join-step-line active"></div>
                  </div>
                </div>
                <div class="col-10">
                  <div class="h-card-box bgimg-1 rounded-3 mt-1">
                    <div class="join-step-card px-2 py-3">
                      <h5>第二步: </h5>
                      <p>
                        在钱包应用中创建好你的tron钱包并向其中充值适当的TRX（10枚以上）和100枚USDT资产用于下一步的投资。
                      </p>

                    </div>
                  </div>
                </div>
              </div>
              <!-- step3 start -->
              <div class="row">
                <div class="col-2">
                  <div class="join-step d-flex align-content-between flex-column">
                    <div class="join-step-num active">3</div>
                    <div class="join-step-line active"></div>
                  </div>
                </div>
                <div class="col-10">
                  <div class="h-card-box bgimg-1 rounded-3 mt-1">
                    <div class="join-step-card px-2 py-3">
                      <h5>第三步: </h5>
                      <p>
                        打开你下载好的钱包,进入到DAPP浏览器,粘贴官网地址,打开网页后,设置好您要投资的数量,填写邀请人的TRX地址,进入后点击页面中的【加入】按钮,即可完成投资操作。
                      </p>

                    </div>
                  </div>
                </div>
              </div>
              <!-- step4 start -->
              <div class="row">
                <div class="col-2">
                  <div class="join-step d-flex align-content-between flex-column">
                    <div class="join-step-num active">4</div>
                    <div class="join-step-line active"></div>
                  </div>
                </div>
                <div class="col-10">
                  <div class="h-card-box bgimg-1 rounded-3 mt-1">
                    <div class="join-step-card px-2 py-3">
                      <h5>第四步: </h5>
                      <p>
                        您可通过点击网页中【提币】按钮进行提币,智能合约会立即将您的收益计算完成并转入到您的钱包中
                      </p>

                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
        <!-- 如何加入 end -->
        <!-- footer end -->
        <!-- <div class="row mt-4 pb-5">
          <div class="col">
            <router-link to="/About" class="text-decoration-none mx-2 text-main">联系我们</router-link>
            <router-link to="/About" class="text-decoration-none mx-2 text-main">NFT专题</router-link>
            <router-link to="/About" class="text-decoration-none mx-2 text-main">我的记录</router-link>
          </div>
        </div> -->
        <!-- footer end -->

      </div>
    </div>

    <!-- 弹窗 -->

    <!-- <van-dialog v-model="show" title="标题" show-cancel-button>
      <img src="https://img01.yzcdn.cn/vant/apple-3.jpg" />
    </van-dialog> -->

    <!-- 中奖弹窗 start -->
    <van-config-provider :theme-vars="themeVarsForReward">
      <van-popup :show="showLottery" :round="true" class="reward-modal-popup">
        <div class="reward-modal-box">
          <div class="reward-modal">
            <div class="reward-modal-body">
              <div class="gxzj-reward">
                <img src="../assets/img/gxzj.png" alt="">
              </div>
            </div>

            <div class="gxzj-tip d-block mx-auto w-75">
              <h4 class="text-center py-3 ">恭喜抽中了{{selectLotteryItem.cardType}}卡</h4>
            </div>

            <div class="gxzj-image">

              <img :src="selectLotteryItem.path" style="min-height:5em" class="d-block w-25 mx-auto" alt="">
              <div class="text-center my-2">{{selectLotteryItem.cardType}}</div>
            </div>

            <button class="btn mx-auto d-block gxzj-sx" @click="closeReward">
              收下
            </button>
          </div>
          <div class="gxzj-close mx-auto d-block" @click="closeReward"></div>
        </div>
      </van-popup>
    </van-config-provider>

    <!-- 中奖弹窗 end -->

    <!-- 绑定弹窗提示 start -->
    <van-popup :show="bindInputPopup" :round="true" :style="{ paddingTop: '2em',paddingBottom: '2em',width:'80%',backgroundColor:'#020a1e' }">
      <h3 class="text-center mb-4">绑定推荐人地址</h3>
      <div class="text-center my-5">
        <input type="text" v-model="recommendAddress" class="su-input" placeholder="请绑定推荐人地址">
      </div>
      <div class="d-flex justify-content-around">
        <button class="btn btn-primary btn-sm w-25" type="button" @click="confirmBind">确认</button>
        <button class="btn btn-primary btn-sm border-0 w-25" type="button" style="background-color:#495797" @click="cancelBind">取消</button>
      </div>
    </van-popup>
    <!-- 绑定弹窗提示 end -->

    <!-- 充值输入弹窗 start -->
    <van-popup :show="rechargeInputPopup" :round="true" :style="{ paddingTop: '2em',paddingBottom: '2em',width:'80%',backgroundColor:'#020a1e' }">
      <h3 class="text-center mb-4">SU充值</h3>
      <div class="text-center my-5">
        <input type="text" v-model="rechargeAmount" class="su-input" placeholder="请输入充值数量">
      </div>
      <div class="d-flex justify-content-around">
        <button class="btn btn-primary btn-sm w-25" type="button" @click="onConfirmRecharge">确认</button>
        <button class="btn btn-primary btn-sm border-0 w-25" type="button" style="background-color:#495797" @click="onCloseRecharge">取消</button>
      </div>
    </van-popup>
    <!-- 充值输入弹窗 end -->

    <!-- 提币输入弹窗 start -->
    <van-popup :show="withdrawInputPopup" :round="true" :style="{ paddingTop: '2em',paddingBottom: '2em',width:'80%',backgroundColor:'#020a1e' }">
      <h3 class="text-center mb-4">{{withdrawCoin}}提币</h3>
      <div class="text-center my-5">
        <input type="text" v-model="withdrawAmount" class="su-input" :placeholder="'请输入提币数量'+ withdrawCoin">
      </div>
      <div class="d-flex justify-content-around">
        <button class="btn btn-primary btn-sm w-25" type="button" @click="onConfirmWithdraw">确认</button>
        <button class="btn btn-primary btn-sm border-0 w-25" type="button" style="background-color:#495797" @click="onCloseWithdraw">取消</button>
      </div>
    </van-popup>
    <!-- 提币输入弹窗 end -->

    <!-- 卖出弹窗提示 start -->
    <van-popup :show="soldPopup" :round="true" custom-class="tips-popup" :style="{ paddingTop: '2em',paddingBottom: '2em',width:'80%',backgroundColor:'#020a1e' }">
      <h3 class="text-center mb-4">提示</h3>
      <p class="text-center my-5 border-1">你确定按照60%的比例卖出此星球卡吗？</p>
      <div class="d-flex justify-content-around">
        <button class="btn btn-primary btn-sm w-25" @click="confirmSold">确认</button>
        <button class="btn btn-primary btn-sm border-0 w-25" style="background-color:#495797" @click="closeSold">取消</button>
      </div>
    </van-popup>
    <!-- 卖出弹窗提示 end -->

    <!-- 抽奖提示 start -->
    <van-popup :show="lotteryFeePopup" :round="true" custom-class="tips-popup" :style="{ paddingTop: '2em',paddingBottom: '2em',width:'80%',backgroundColor:'#020a1e' }">
      <h3 class="text-center mb-4">提示</h3>
      <p class="text-center my-5 border-1">你确定消费 {{lotteryFee}} SU？</p>
      <div class="d-flex justify-content-around">
        <button class="btn btn-primary btn-sm w-25" @click="confirmLotteryFeePopup">确认</button>
        <button class="btn btn-primary btn-sm border-0 w-25" style="background-color:#495797" @click="closeLotteryFeePopup">取消</button>
      </div>
    </van-popup>
    <!-- 抽奖提示 end -->

    <!-- 兑换弹窗提示 start -->
    <van-popup :show="exchangePopup" :round="true" custom-class="tips-popup" :style="{ paddingTop: '2em',paddingBottom: '2em',width:'80%',backgroundColor:'#020a1e' }">
      <h3 class="text-center mb-4">提示</h3>
      <p class="text-center my-5 border-1">你确定兑换此星球卡吗？</p>
      <div class="d-flex justify-content-around">
        <button class="btn btn-primary btn-sm w-25" @click="confirmExchangePopup">确认</button>
        <button class="btn btn-primary btn-sm border-0 w-25" style="background-color:#495797" @click="closeExchangePopup">取消</button>
      </div>
    </van-popup>
    <!-- 兑换弹窗提示 end -->

  </div>
</template>

<script lang="ts">
import { getCurrentAddress, STW } from '@/service/tw'
import { reactive, toRefs } from '@vue/reactivity'
import { onMounted } from '@vue/runtime-core'
import { apis, fetchPersonalData, postRequest } from '@/common/ts/request'
import { Toast } from 'vant'
import { useStore } from 'vuex'
import ClipboardJS from 'clipboard'
import tp from 'tp-js-sdk'
import { useRouter } from 'vue-router'
import { BigNumber } from 'bignumber.js'

export default {
  setup() {
    const router = useRouter()
    onMounted(async () => {
      await init()
      initCopyHander('.copy-btn1')
      initCopyHander('.copy-btn2')
    })

    //获取地址
    const getAddress = async () => {
      let address = ''
      if (tp.isConnected()) {
        const { data } = await tp.getCurrentWallet()
        address = data.address
        console.log('tp address', address)
      } else {
        address = getCurrentAddress()
        console.log('tronWeb address', address)
      }

      if (!address) {
        Toast.fail('获取地址失败，请重试')
      }
      return address
    }

    // 复制操作
    const initCopyHander = (cls) => {
      //复制
      const clipboard = new ClipboardJS(cls)
      clipboard.on('success', function (e) {
        console.info('Text:', e.text)
        e.clearSelection()
        Toast.success('复制成功')
      })

      clipboard.on('error', function (e) {
        console.error('Action:', e.text)
        Toast.fail('复制失败')
      })
    }

    const store = useStore() // 获取vuex实例
    const state = reactive({
      showLottery: false,
      lotteryFeePopup: false,
      lotteryFee: '',
      soldPopup: false,
      selectLotteryItem: {},
      exchangePopup: false,
      bindInputPopup: false,
      recommendAddress: '',
      bannerImgs: [],
      exchangeList: [],
      personalData: {},
      mysteryLists: [],
      selectSoldItem: {},
      selectExchangeItem: {},
      joinPrice: 100,
      withdrawCoin: '',
      withdrawCoinId: 1,
      withdrawAmount: '',
      withdrawInputPopup: false,
      intervalID: 0,
      rechargeInputPopup: false,
      rechargeAmount: '',
      rechargeUSDTCoin: 'USDT',
      rechargeSUCoin: 'SU',
      isActivated: false,
    })

    const themeVarsForReward = {
      popupBackgroundColor: 'transparent',
    }

    const init = async () => {
      const address = await getAddress()
      // const address = 'TRdZ8AFumEwpqQWJg9x3ZF1MDXWoLuBhjD'
      console.log('init', address)

      if (address) {
        //获取token
        const loginParams = {
          address: address,
          code: '',
        }

        const { data } = await postRequest(apis.login, loginParams)
        //保存token
        store.commit('setToken', data.token)

        //获取用户信息
        {
          const { data } = await postRequest(apis.user)
          //弹窗提示绑定
          if (data.isActivate != 'yes') {
            showBindInputPopup()
          } else {
            state.isActivated = true
          }
        }
        await getBannerImgs()
        await getExchangeList()
        await getPersonalData()
        await getMystery()
        await getLotteryFee()
      }
    }

    //打开抽奖
    const openReward = async () => {
      Toast.loading({
        message: '正在抽奖...',
        forbidClick: true,
      })
      const { data } = await postRequest(apis.lottery)
      state.selectLotteryItem = data
      state.showLottery = true
      Toast.clear()
    }
    //关闭抽奖(收下抽奖)
    const closeReward = () => {
      state.showLottery = false
    }

    //打开抽奖费用
    const openLotteryFeePopup = async () => {
      state.lotteryFeePopup = true
    }
    //确认抽奖费用
    const confirmLotteryFeePopup = async () => {
      state.lotteryFeePopup = false
      openReward()
    }
    //关闭抽奖费用
    const closeLotteryFeePopup = () => {
      state.lotteryFeePopup = false
    }

    /**
     * 显示卖出popup
     */
    const showSoldPopup = (item: any) => {
      state.soldPopup = true
      state.selectSoldItem = item
      console.log('showSoldPopup', item.cardType)
    }

    /**
     * 打开兑换
     */
    const openExchangePopup = (item: any) => {
      state.selectExchangeItem = item
      state.exchangePopup = true
    }
    /**
     * 取消兑换
     */
    const closeExchangePopup = () => {
      state.exchangePopup = false
    }
    /**
     * 确认兑换
     */
    const confirmExchangePopup = async () => {
      await postExchange((state.selectExchangeItem as any).id)
    }
    /**
     * 取消出售
     */
    const closeSold = () => {
      state.soldPopup = false
    }
    /**
     * 确认出售
     */
    const confirmSold = async () => {
      await postSellCard((state.selectSoldItem as any).cardType)
    }

    // 绑定
    const showBindInputPopup = async () => {
      state.bindInputPopup = true
    }

    const confirmBind = async () => {
      const bindInfo = await postRequest(apis.bind, {
        inviteAddress: state.recommendAddress,
      })
      console.log(bindInfo)
      cancelBind()
      Toast.success({
        message: '激活成功',
        onClose: () => {
          console.log('onclose')
          window.location.reload()
        },
      })
    }
    const cancelBind = async () => {
      state.bindInputPopup = false
    }

    // 获取banner
    const getBannerImgs = async () => {
      const resp = await postRequest(apis.banner)
      state.bannerImgs = resp.data
    }

    // 兑换列表
    const getExchangeList = async () => {
      const resp = await postRequest(apis.mysteryExchange)
      state.exchangeList = resp.data
    }
    // 个人数据
    const getPersonalData = async () => {
      const data = await fetchPersonalData()
      state.personalData = data
      console.log('getPersonalData：', data)
    }
    // 卖出卡牌
    const postSellCard = async (cardType: string) => {
      closeSold()

      Toast.loading({
        message: '出售中...',
        forbidClick: true,
      })

      const { data } = await postRequest(apis.sellCard, {
        cardType: cardType,
      })

      console.log(data)
      if (data) {
        Toast.success('出售成功')
      }
    }
    // 兑换卡牌
    const postExchange = async (id: number) => {
      closeExchangePopup()

      Toast.loading({
        message: '兑换中...',
        forbidClick: true,
      })

      const { data } = await postRequest(apis.exchange, {
        id: id,
      })

      console.log(data)
      if (data) {
        Toast.success('兑换成功')
      }
    }

    // 拥有卡牌列表
    const getMystery = async () => {
      const resp = await postRequest(apis.mystery)
      state.mysteryLists = resp.data
      console.log(resp)
    }
    // 获取抽奖费用
    const getLotteryFee = async () => {
      const { data } = await postRequest(apis.lotteryFee)
      state.lotteryFee = data
    }

    //新人加入检查 USDT充值
    const onJoin = async () => {
      if (!state.isActivated) {
        Toast.fail('未激活账户，不可操作')
        return false
      }

      const price = state.joinPrice
      const { data } = await postRequest(apis.checkInvestment)
      if (data !== true) {
        Toast.fail(data)
        return false
      }

      const result = await transferIn(price, state.rechargeUSDTCoin)
      if (result) {
        Toast.success({
          message: '加入成功',
        })
      } else {
        Toast.fail('加入失败')
      }
    }

    /**
     * 转出
     */
    const transferIn = async (u: number, t: string) => {
      const amount = u * Math.pow(10, 6)
      const contractAddress =
        t == state.rechargeUSDTCoin
          ? process.env.VUE_APP_JOIN_USDT_ADDRESS
          : process.env.VUE_APP_JOIN_SU_ADDRESS
      const acceptAddress = process.env.VUE_APP_JOIN_ACCEPT_ADDRESS

      const accountInfo = await STW.trx.getAccount()
      console.log('accountInfo', accountInfo)
      const from = accountInfo.address
      console.log('balance,amount', accountInfo.balance, amount)

      //获取合约
      const coinContract = await STW.contract().at(contractAddress)
      const coinContractBalance = await coinContract.balanceOf(from).call()
      console.log([
        'coinContractBalance',
        coinContractBalance,
        coinContractBalance.toString(),
      ])
      var balanceBN = new BigNumber(coinContractBalance)
      if (balanceBN.gte(amount)) {
        console.log('balanceBN 足够')
      } else {
        console.log('balanceBN 不足')
      }

      const hash = await coinContract.transfer(acceptAddress, amount).send({
        feeLimit: STW.toSun(100), //调用合约方法消耗最大数量的SUN。上限是 1000 TRX。(1TRX = 1,000,000SUN)	Integer
        shouldPollResponse: false,
      })
      if (hash) {
        console.log('转出成功', hash)
        return true
      } else {
        console.log('转出失败')
        return false
      }
    }

    //提币操作
    const onWithdraw = async (type: number) => {
      state.withdrawCoinId = type
      state.withdrawCoin = type == 1 ? 'SU' : 'USDT'
      state.withdrawInputPopup = true
    }

    // 确认提币
    const onConfirmWithdraw = async () => {
      let withdrawAmount = parseFloat(state.withdrawAmount)

      if (isNaN(withdrawAmount)) {
        Toast.fail('请输入正确的提币数量')
        return
      }

      if (withdrawAmount < 1) {
        Toast.fail('提币数量最少为1')
        return
      }

      let dot = withdrawAmount.toString().indexOf('.') > -1 ? withdrawAmount.toString().split('.')[1].length :0
      if (dot > 4) {
        Toast.fail('提币数量最多为4位小数')
        return
      }

      onCloseWithdraw()

      Toast.loading({
        message: '提币中...',
        forbidClick: true,
      })

      const { data } = await postRequest(apis.withdraw, {
        coinId: state.withdrawCoinId,
        number: withdrawAmount,
      })
      console.log(data)
      if (data) {
        state.withdrawAmount = ''
        getPersonalData()
        Toast.success('提币成功')
      }
    }

    // 关闭提币弹窗
    const onCloseWithdraw = async () => {
      state.withdrawInputPopup = false
    }

    // 确认充值SU
    const onConfirmRecharge = async () => {
      if (!state.isActivated) {
        Toast.fail('未激活账户，不可操作')
        return false
      }

      let amount = 0.0001
      if (state.rechargeAmount != 'SUAPPTEST') {
        amount = parseFloat(state.rechargeAmount)
        if (isNaN(amount) || amount < 100) {
          Toast.fail('充值不能小于100SU')
          return false
        }
      }
      const result = await transferIn(amount, state.rechargeSUCoin)

      if (result) {
        Toast.success({
          message: '充值成功',
          onClose: () => {
            state.rechargeAmount = ''
            onCloseRecharge()
            getPersonalData()
          },
        })
      } else {
        Toast.fail('充值失败')
      }
    }

    // 打开充值弹窗
    const onOpenRecharge = async () => {
      if (!state.isActivated) {
        Toast.fail('未激活账户，不可操作')
        return false
      }

      state.rechargeInputPopup = true
    }
    // 关闭充值弹窗
    const onCloseRecharge = async () => {
      state.rechargeInputPopup = false
    }

    // su交易
    const suTransaction = () => {
      console.log('suTransaction')
      window.location.href = 'https://justswap.link/?utm_source=tokenpocket'
    }

    return {
      ...toRefs(state),
      openReward,
      closeReward,
      showSoldPopup,
      closeSold,
      confirmSold,
      showBindInputPopup,
      confirmBind,
      cancelBind,
      getBannerImgs,
      getExchangeList,
      getMystery,
      postSellCard,
      themeVarsForReward,
      confirmExchangePopup,
      closeExchangePopup,
      openExchangePopup,
      openLotteryFeePopup,
      confirmLotteryFeePopup,
      closeLotteryFeePopup,
      onJoin,
      onWithdraw,
      onConfirmWithdraw,
      onCloseWithdraw,
      onConfirmRecharge,
      onCloseRecharge,
      onOpenRecharge,
      suTransaction,
    }
  },
}
</script>

<style lang="scss" scoped>
.h-box {
  .bg-black {
    background-color: #000000;
  }
  .h-lang {
    display: inline-block;
    height: 1em;
    margin-left: 0.5em;
    img {
      height: 50%;
    }
  }

  .carousel-indicators [data-bs-target] {
    width: 20px !important;
    height: 6px !important;
    border-radius: 3px;
    border-top: 0px;
    border-bottom: 0px;
  }

  .h-box-start {
    .h-box-star-sold {
      .h-star {
        width: 23%;
        position: relative;
        .h-code {
          position: absolute;
          top: 0;
        }
        .h-img {
          height: 7em;
          border-bottom: 1px solid #042151;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;
          img {
            height: 6em;
          }
        }
      }
    }
  }

  .h-card {
    .h-card-title {
      background: transparent url('../assets/img/q5.png') center left no-repeat;
      background-size: 1.2em;
      padding-left: 30px;
    }
    .h-rule-box {
      max-height: 25em;
      overflow-y: scroll;
    }
  }

  .copy-img {
    display: block;
    height: 1em;
  }
  .join-btn {
    background-color: #495797;
    width: 60%;
    margin: auto;
  }
  .join-input {
    &::placeholder {
      color: #a8d0fc;
    }
  }
  .join-step {
    height: 100%;
    align-items: center;
    justify-content: center;
    .join-step-num {
      height: 2em;
      width: 2em;
      border: 1px solid #04102b;
      border-radius: 2em;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #04102b;
    }
    .join-step-line {
      height: 60%;
      border-left: 1px solid #04102b;
      margin: 1em 0;
    }
    .active {
      border-color: #164ed2;
    }
  }
}

.reward-modal-box {
  .reward-modal {
    background: transparent url('../assets/img/m0.png') no-repeat;
    height: 20em;
    width: 20em;
    background-size: 100% 100%;
    .reward-modal-body {
      margin-top: 2em;
      border-radius: 1em;
      position: relative;
      z-index: 2088;
      height: 3em;
      .gxzj-reward {
        width: 100%;
        height: 5em;
        top: -3em;
        position: absolute;
        z-index: 2088;
        background-color: transparent;
        img {
          margin: auto;
          display: block;
          height: 6em;
        }
      }
    }
    .gxzj-tip {
      background: transparent url('../assets/img/jb.png') center no-repeat;
      background-size: 100%;
      color: #fff000;
    }
    .gxzj-sx {
      background: transparent url('../assets/img/sx.png') center no-repeat;
      background-size: cover;
      width: 8em;
      height: 3em;
      color: #fff;
    }
  }
  .gxzj-close {
    background: transparent url('../assets/img/delxx.png') center no-repeat;
    background-size: cover;
    width: 3em;
    height: 3em;
    display: block;
    margin-top: 2em;
  }
}
</style>
